package com.seqb.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.seqb.annotation.Log;
import com.seqb.common.ResultVo;
import com.seqb.common.config.SeqbConfig;
import com.seqb.common.controller.BaseController;
import com.seqb.common.utils.JwtUtils;
import com.seqb.common.utils.RedisUtils;
import com.seqb.manage.user.dao.UserDao;
import com.seqb.manage.user.domain.UserDO;
import com.seqb.utils.Md5Utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;

/**
 * @author lilinshen
 * @title 登录的controller
 * @description 请填写相关描述
 * @date 2019/11/12
 */
@Controller
public class LoginController extends BaseController {
    @Autowired
    private UserDao userDao;
    @Autowired
    private Producer producer;
    @Autowired
    private SeqbConfig seqbConfig;
    @Autowired
    private RedisUtils redisUtils;

    @Log("登录")
    @GetMapping("/login")
    @ResponseBody
    ResultVo getLogin() {
        //验证验证码是否正确
        boolean captchaOpen = seqbConfig.isCaptchaOpen();
        try {
            String uuid = UUID.randomUUID().toString();
            return ResultVo.ok().put("uuid", uuid).put("captchaOpen", captchaOpen);
        } catch (AuthenticationException e) {
            return ResultVo.error(e.getMessage());
        }
    }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    ResultVo postLogin(String account, String password, String captcha, String uuid) {
        //验证验证码是否正确
        if (seqbConfig.isCaptchaOpen()) {
            String code = (String) redisUtils.get(uuid);
            if (StringUtils.isEmpty(code)) {
                return ResultVo.error("验证码已失效！");
            }
            if (StringUtils.isEmpty(captcha) || !captcha.equalsIgnoreCase(code)) {
                return ResultVo.error("验证码错误！");
            }
        }
        password = Md5Utils.encrypt(password);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", account);
        UserDO user = userDao.selectOne(queryWrapper);
        if (user == null) {
            return ResultVo.error("账号不存在！");
        }
        if (!user.getPassword().equals(password)) {
            return ResultVo.error("密码不正确！");
        }
        if ("0".equals(user.getState())) {
            return ResultVo.error("账号已被锁定！");
        }
        try {
            String token = JwtUtils.sign(user.getAccount(), user.getPassword());
            user.setPassword(null);
            return ResultVo.ok("登录成功！").put("user", user).put("token", token);
        } catch (AuthenticationException e) {
            return ResultVo.error(e.getMessage());
        }
    }

    /**
     * 生成验证码
     */
    @RequestMapping("/captcha")
    public void captcha(String uuid, HttpServletResponse response) {
        if (StringUtils.isEmpty(uuid)) {
            return;
        }
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        String captcha = producer.createText();
        BufferedImage bi = producer.createImage(captcha);
        //存到redis,120秒有效
        redisUtils.set(uuid, captcha, 120);
        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(bi, "jpg", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
